package com.haredot.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.haredot.constraint.RbacConst;
import com.haredot.dto.BindUserRoleDto;
import com.haredot.oss.properties.OssProperties;
import com.haredot.service.UserService;
import com.haredot.utils.UploadUtils;
import com.haredot.utils.ValidUtils;
import com.haredot.vo.PageVo;
import com.haredot.vo.R;
import com.haredot.vo.UserVo;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@EnableConfigurationProperties(OssProperties.class)
public class UserController {

    @Resource
    private OssProperties ossProperties ;

    @Resource
    private UserService userService ;

    @Resource
    private OSS ossClient ;

    @PostMapping("/upload")
    @PreAuthorize("hasAnyAuthority('user:add', 'user:update')")
    public R<?> upload(@RequestParam("avatar") MultipartFile multipartFile) throws Exception {
        // 获取 要存储在 磁盘上的文件名
        String filename = "avatar/" + UUID.randomUUID() + multipartFile.getOriginalFilename();
        // 构建 PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucketName(), filename, multipartFile.getInputStream());
        // 上传文件到网盘
        ossClient.putObject(putObjectRequest);
        // 返回结果
        return R.ok().data(Map.of("url", filename));
    }

    @GetMapping("/queryOrgAndPositionOrUserData")
    @PreAuthorize("hasAnyAuthority('user:add', 'user:update')")
    public R<?> queryOrgAndPositionOrUserData(@RequestParam(value = "userId", required = false) Long userId) {

        return userService.queryOrgAndPositionOrUserData(userId);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('user:add')")
    public R<?> addUser(@RequestBody @Validated UserVo userVo, BindingResult bindingResult) {
        return ValidUtils.toResult(bindingResult, ()-> userService.saveUser(userVo));
    }

    @PutMapping("/update/{id}")
    @PreAuthorize("hasAuthority('user:update')")
    public R<?> addUser(@PathVariable("id") Long id,
                        @RequestBody @Validated UserVo userVo, BindingResult bindingResult) {
        userVo.setId(id);
        return ValidUtils.toResult(bindingResult, ()-> userService.updateUser(userVo));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('user:query', 'user')")
    public R<PageVo> list(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                          @RequestParam(value = "rows", required = false, defaultValue = "10") Integer rows,
                          @RequestParam Map<String, Object> searchParams) {
        PageVo pageVo = new PageVo(page, rows) ;

        return userService.queryUsersByPage(pageVo, searchParams);
    }

    @DeleteMapping("/del/{userId}")
    @PreAuthorize("hasAuthority('user:delete')")
    public R<?> deleteUser(@PathVariable("userId") Long userId) {
        return userService.removeUser(userId) ;
    }


    @GetMapping("/{userId}/roles")
    public R<BindUserRoleDto> queryUserRoles(@PathVariable("userId") Long userId) {

        return userService.queryRolesRefUser(userId);
    }

    @PutMapping("/{userId}/bindRole")
    @PreAuthorize("hasAuthority('user:apply:role')")
    public R<?> bindUserRoles(@PathVariable("userId") Long userId, @RequestBody List<Long> roles) {

        return userService.bindRolesRefUser(userId, roles);
    }
}
